package com.ship.system.buesiness;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ship.common.core.constant.ShipApiConstants;
import com.ship.common.core.enums.NotifyType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <b>MoveCloudBusiness</b>
 *
 * @description: MoveCloudBusiness <br>
 * @date: 2024/4/9 08:58 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class MoveCloudBusiness {
    private static final Logger logger = LoggerFactory.getLogger(MoveCloudBusiness.class);

    @Value("${moving_cloud.url}")
    private String movingCloudUrl;

    @Value("${moving_cloud.appId}")
    private String movingCloudAppId;

    @Value("${moving_cloud.token}")
    private String movingCloudToken;

    public String sendMoveCloudMessage(NotifyType messageType, String userName, String message,String messageUrl) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        URL url = new URL(movingCloudUrl);
        String auth = movingCloudAppId+":"+movingCloudToken;
        String authentication = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());
        //第二步：打开一个通向服务地址的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //第三步：设置参数
        //3.1发送方式设置：POST必须大写
        connection.setRequestMethod("POST");
        //3.2设置数据格式：content-type
        connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        connection.setRequestProperty("AppId",movingCloudAppId);
        connection.setRequestProperty("Authorization",authentication);
        connection.setRequestProperty("SOAPAction","application/soap+xml");
        //3.3设置输入输出，因为默认新创建的connection没有读写权限，
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //第四步：组织SOAP数据，发送请求，
        String soapXML = getXML("pushNotify",messageType,userName,message,messageUrl);
        //将信息以流的方式发送出去
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());
        //第五步：接收服务端响应，打印
        int responseCode = connection.getResponseCode();
        logger.info("推送移动云消息返回结果:{}"+ JSONUtil.parse(responseCode));
        System.out.println(responseCode);
        if(200 == responseCode){//表示服务端响应成功
            //获取当前连接请求返回的数据流
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String temp = null;
            while(null != (temp = br.readLine())){
                sb.append(temp);
            }

            /**
             * 打印结果
             */
            logger.info("获取返回结果:{}"+JSONUtil.parse(sb.toString()));
            try{
                //对返回的数据进行JSON格式化
                System.out.println(xml2Json(sb.toString()));
            }catch (Exception e){
                e.printStackTrace();
            }
            is.close();
            isr.close();
            br.close();
        }
        os.close();
        return null;
    }


    //请求入参
    public static String getXML(String method,NotifyType messageType,String userName,String message,String url){
        String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://mobile.cnooc.com.cn/api/common\">"
                +"<soapenv:Header/>"
                +"<soapenv:Body>  "
                +"<com:"+method+">"//方法名
                +"<senderAccount>"+"qd_lngyscbdd_push"+"</senderAccount>"
                +"<recipientAccount>"+userName+"</recipientAccount>"
                +"<notifyType>"+messageType+"</notifyType>"
                +"<message>"+message+"</message>"
                +"<extraInfo>"
                +"<entry>"
                +"<key>"+"url"+"</key>"
                +"<value>"+url+"</value>"
                +"</entry>"
                +"</extraInfo>"
                +"</com:"+method+">"
                +"</soapenv:Body>"
                +"</soapenv:Envelope>";
        return soapXML;
    }

    /**
     * xml转json
     *
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml转json
     *
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public void ceshiPlushMoveCloudMessage(String messageType, String userName, String message, String messageUrl) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        if ("LINK".equals(messageType)){
            sendMoveCloudMessage(NotifyType.LINK,userName,message,messageUrl);
        }else if ("MESSAGE".equals(messageType)){
            sendMoveCloudMessage(NotifyType.MESSAGE,userName,message,messageUrl);
        }
    }
}
